import React, { useState, useEffect } from "react";
import { Button, Collapse, Input, Modal } from "antd";
import type { CollapseProps } from "antd";
import { getAuthorCollectionList, userDeleteFolder } from "@/apis/userApi.ts";
import UserCollectionItemToChange from "./UserCollectionItemToChange";
import { userAddFolder } from "@/apis/userApi.ts";
import { useDispatch } from "react-redux";
import { setUserCollectionList } from "@/store/UserInfo/index.ts";

function UserCollectionListToChange() {
  const dispatch = useDispatch();

  const [folderData, setFolderData] = useState<CollapseProps["items"]>();

  const onChange = (key: string | string[]) => {
    console.log(key); // 这里的key就是被展开的收藏夹的key的值
  };

  // 提示框是否展示
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 需要删除的收藏夹名称
  const [folderNameToDelete, setFolderNameToDelete] = useState("");

  // 展示提示框
  const showModal = (e: React.MouseEvent, folderName: string) => {
    e.stopPropagation(); // 阻止事件冒泡，防止点击到其他地方关闭提示框

    // 设置需要删除的收藏夹名称
    setFolderNameToDelete(folderName);

    // 打开提示框
    setIsModalOpen(true);
  };

  // 提示框点击确认
  const handleOk = async () => {
    const res = await userDeleteFolder(folderNameToDelete);

    // 如果删除成功，刷新页面
    if (res.code === 200) {
      // 重新获取文件夹数据
      await fetchFolderData();
    }

    // 重置需要删除的收藏夹名称
    setFolderNameToDelete("");

    // 关闭提示框
    setIsModalOpen(false);
  };

  // 提示框点击取消
  const handleCancel = () => {
    // 重置需要删除的收藏夹名称
    setFolderNameToDelete("");

    // 关闭提示框
    setIsModalOpen(false);
  };

  // 获取文件夹数据
  const fetchFolderData = async () => {
    // 先清除一下之前的数据
    setFolderData([]);

    // 获取文件夹数据
    const res = await getAuthorCollectionList();

    res.data?.forEach((item) => {
      setFolderData((prev) => {
        return [
          ...(prev || []),
          {
            key: item._id,
            label: (
              <div>
                {item.folderName}{" "}
                <Button
                  type="link"
                  onClick={(e) => showModal(e, item.folderName)}
                >
                  删除
                </Button>
              </div>
            ),
            children: (
              <UserCollectionItemToChange
                reloadData={fetchFolderData}
                collectItem={item.collectItem}
                folderName={item.folderName}
              />
            ),
          },
        ];
      });
    });

    // 将数据存储到store中
    dispatch(setUserCollectionList(res.data || []));
  };

  // 页面加载完成后，获取文件夹数据
  useEffect(() => {
    fetchFolderData();
  }, []);

  /* 添加收藏夹逻辑 */

  // 新增文件夹提示框是否展示
  const [isModalOpenToFolder, setIsModalOpenToFolder] = useState(false);
  // 新增文件夹名称
  const [newFolderName, setNewFolderName] = useState("");

  // 展示新增文件夹提示框
  const showModalToFolder = () => {
    setIsModalOpenToFolder(true);
  };

  // 新增文件夹提示框点击确认
  const handleOkToFolder = async () => {
    // 调用接口新增文件夹
    const res = await userAddFolder(newFolderName);

    // 如果新增成功，刷新页面
    if (res.code === 200) {
      // 重新获取文件夹数据
      await fetchFolderData();
    }

    // 重置新增文件夹名称
    setNewFolderName("");

    // 关闭提示框
    setIsModalOpenToFolder(false);
  };

  // 新增文件夹提示框点击取消
  const handleCancelToFolder = () => {
    setIsModalOpenToFolder(false);
  };

  return (
    <div>
      <div>
        <Button type="link" onClick={showModalToFolder}>
          新增文件夹
        </Button>{" "}
      </div>
      {/* <div style={{ maxHeight: "400px", overflowY: "auto" }}> */}
      <div>
        <Collapse items={folderData} onChange={onChange} />
      </div>
      <Modal
        title="注意"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <p>确认删除收藏夹：{folderNameToDelete}？</p>
      </Modal>
      <Modal
        title="新增文件夹"
        open={isModalOpenToFolder}
        onOk={handleOkToFolder}
        onCancel={handleCancelToFolder}
      >
        <Input
          value={newFolderName}
          onChange={(e) => setNewFolderName(e.target.value)}
          placeholder="请输入文件夹名称"
        />
      </Modal>
    </div>
  );
}

export default UserCollectionListToChange;
